﻿using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace echuCMS
{
    public partial class FormCustomerMain : Form
    {
        private BindingSource bsCustomerMain = new BindingSource();
        private BindingSource bsCustomerContract = new BindingSource();
        private BindingSource bsCustomerFinance = new BindingSource();
        private BindingSource bsCustomerDeliver = new BindingSource();
        private CustomerMain customerMain = new CustomerMain();
        private CustomerContract customerContract = new CustomerContract();
        private List<CustomerContract> customerContracts = new List<CustomerContract>();
        private CustomerDeliver customerDeliver = new CustomerDeliver();
        private List<CustomerDeliver> customerDelivers = new List<CustomerDeliver>();
        private CustomerFinance customerFinance = new CustomerFinance();
        private List<CustomerFinance> customerFinances = new List<CustomerFinance>();
        public FormCustomerMain()
        {
            InitializeComponent();
        }

        private void FormCustomerMain_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            this.comboBoxContractSex.SelectedIndex = 0;
            this.dataGridViewContract.AutoGenerateColumns = false;
            this.dataGridViewCustomerMain.AutoGenerateColumns = false;
            this.dataGridViewDeliver.AutoGenerateColumns = false;
            this.dataGridViewFinance.AutoGenerateColumns = false;
            this.buttonSave.Enabled = false;
            buttonEdit.Enabled = false;
            buttonDelete.Enabled = false;
            //加载已经有的公共池客户
            //getAllCustomerMain();
        }

        private void getAllCustomerMain()
        {
          List<CustomerMain> customerMains = CustomerMainService.getAllCustomerMain();
            bsCustomerMain.DataSource = customerMains;
            this.dataGridViewCustomerMain.DataSource = bsCustomerMain;
        }


        /// <summary>
        /// 清空所有控件内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void clearAllControlText()
        //{
        //    this.textBoxCustomerCode.Text = "";
        //    this.textBoxCustomerName.Text = "";
        //    this.textBoxTrades.Text = "";

        //    this.textBoxCustomerOrigin.Text = "";
        //    this.textBoxCustomerType.Text = "";
        //    this.textBoxCustomerLevel.Text = "";
        //    this.textBoxCustomerOperateAddress.Text = "";
        //    this.textBoxCustomerAttribute.Text = "";
        //    this.textBoxCustomerSignAddress.Text = "";
        //    this.textBoxCustomerEmail.Text = "";

        //    this.textBoxContactTelephone.Text = "";
        //    //this.textBoxContractBirthday.Text = "";
        //    this.textBoxContractPostion.Text = "";
        //    this.textBoxContractQq.Text = "";
        //    this.comboBoxContractSex.SelectedIndex = 0;
        //    this.textBoxContractWeChat.Text = "";
        //}
        private void FormCustomerMain_Resize(object sender, EventArgs e)
        {
            /////
            //try
            //{
            //    this.tabPageCustomer.Width = this.Width - 20;

            //}
            //catch
            //{
                
            //}
            //finally
            //{ }
        }

        private void FormCustomerMain_ResizeEnd(object sender, EventArgs e)
        {
            //try
            //{
            //    this.tabPageCustomer.Width = this.Width - 20;

            //}
            //catch
            //{

            //}
            //finally
            //{ }
        }

        private void buttonNew_Click(object sender, EventArgs e)
        {
            //clearAllControlText();
            ClearCntrValue(this);
            clearDataGridView();
        }
        /// <summary>
        /// 保存公共池客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSave_Click(object sender, EventArgs e)
        {
            //封装公共池客户主体对象
            if (string.IsNullOrEmpty(textBoxCustomerCode.Text.Trim()))
            {
                MessageBox.Show("客户编号不可为空");
                return;
            }
            else
            {
                customerMain.CustomerCode = textBoxCustomerCode.Text.Trim();
            }

            if (string.IsNullOrEmpty(textBoxCustomerName.Text.Trim()))
            {
                MessageBox.Show("客户名称不可为空");
                return;
            }
            else
            {
                customerMain.CustomerName = textBoxCustomerName.Text.Trim();
            }
            customerMain.CustomerTrades = textBoxTrades.Text.Trim();
            customerMain.CustomerOrigin = textBoxCustomerOrigin.Text.Trim();
            customerMain.CustomerType = textBoxCustomerType.Text.Trim();
            customerMain.CustomerType = textBoxCustomerType.Text.Trim();
            customerMain.CustomerLevel = textBoxCustomerLevel.Text.Trim();
            customerMain.CustomerOperateAddress = textBoxCustomerOperateAddress.Text.Trim();
            customerMain.CustomerAttribute = textBoxCustomerAttribute.Text.Trim();
            customerMain.CustomerSignAddress = textBoxCustomerSignAddress.Text.Trim();
            customerMain.CustomerEmail = textBoxCustomerEmail.Text.Trim();
            if (customerContracts.Count > 0)
            {
                customerMain.customerContractList = customerContracts;
            }
            if (customerDelivers.Count > 0)
            {
                customerMain.customerDeliverList = customerDelivers;
            }
            if (customerFinances.Count > 0)
            {
                customerMain.customerFinanceList = customerFinances;
            }


            string r = CustomerMainService.insertCustomerMain(customerMain);
            if ("1".EndsWith(r))
            {
                MessageBox.Show("保存成功");
                this.buttonSave.Enabled = false;
                getAllCustomerMain();
                return;
            }
            if ("0".Equals(r))
            {
                MessageBox.Show("保存失败，请联系开发者");
                return;
            }
            MessageBox.Show(r);
        }
        /// <summary>
        /// 下方公共池客户行选中展示具体的联系人，收货，银行等详细信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewCustomerMain_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                buttonSave.Enabled = false;
                buttonEdit.Enabled = true;
                buttonDelete.Enabled = true;
                customerContracts = (bsCustomerMain.Current as CustomerMain).customerContractList;
                bsCustomerContract.DataSource = customerContracts;
                dataGridViewContract.DataSource = bsCustomerContract;
                //显示具体数据
                bsCustomerFinance.DataSource = (bsCustomerMain.Current as CustomerMain).customerFinanceList;
                dataGridViewFinance.DataSource = bsCustomerFinance;
                bsCustomerDeliver.DataSource = (bsCustomerMain.Current as CustomerMain).customerDeliverList;
                dataGridViewDeliver.DataSource = bsCustomerDeliver;
            }
        }

        private void showCustomerToTextBox(CustomerMain customerMain,CustomerContract customerContract,CustomerDeliver customerDeliver,CustomerFinance customerFinance)
        {
            if (customerMain != null)
            {
                textBoxCustomerCode.Text = customerMain.CustomerCode;
                textBoxCustomerName.Text = customerMain.CustomerName;
                textBoxTrades.Text = customerMain.CustomerTrades;
                textBoxCustomerOrigin.Text = customerMain.CustomerOrigin;
                textBoxCustomerType.Text = customerMain.CustomerType;
                textBoxCustomerType.Text = customerMain.CustomerType;
                textBoxCustomerLevel.Text = customerMain.CustomerLevel;
                textBoxCustomerOperateAddress.Text = customerMain.CustomerOperateAddress;
                textBoxCustomerAttribute.Text = customerMain.CustomerAttribute;
                textBoxCustomerSignAddress.Text = customerMain.CustomerSignAddress;
                textBoxCustomerEmail.Text = customerMain.CustomerEmail;
            }
            if (customerContract != null)
            {
                this.comboBoxContractSex.SelectedItem = customerContract.ContractSex;
                this.textBoxContactTelephone.Text = customerContract.ContactTelephone;
                textBoxContractPostion.Text = customerContract.ContractPostion;
                textBoxContractWeChat.Text = customerContract.ContractWeChat;
                textBoxContractQq.Text = customerContract.ContractQq;
                //customerContract.ContractBirthday = DateTime.Parse(textBoxContractBirthday.Text.Trim());
                dateTimePickerCustomerBirthday.Value = customerContract.ContractBirthday.GetValueOrDefault();
            }
            if (customerDeliver != null)
            {

            }
            if (customerFinance != null)
            {

            }
        }

        private void dataGridViewContract_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridViewContract.Columns[e.ColumnIndex].Name != "序号")
            {
                dataGridViewContract.BeginEdit(true);
            }
        }

        private void dataGridViewDeliver_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridViewDeliver.Columns[e.ColumnIndex].Name != "序号")
            {
                dataGridViewDeliver.BeginEdit(true);
            }
        }

        private void dataGridViewFinance_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridViewFinance.Columns[e.ColumnIndex].Name != "序号")
            {
                dataGridViewFinance.BeginEdit(true);
            }
        }

        private void dataGridViewCustomerMain_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridViewCustomerMain.Columns[e.ColumnIndex].Name != "序号")
            {
                dataGridViewCustomerMain.BeginEdit(true);
            }
        }

        private void FormCustomerMain_Shown(object sender, EventArgs e)
        {
            //加载已经有的公共池客户
            getAllCustomerMain();
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            if (bsCustomerMain.Current != null)
            {
               int i = CustomerMainService.updateCustomerMain((bsCustomerMain.Current as CustomerMain));
                if (i > 0)
                {
                    MessageBox.Show("修改成功");
                }
                else
                {
                    MessageBox.Show("修改失败，请联系开发者");
                }
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (bsCustomerMain.Current != null)
            {
                int i = CustomerMainService.deleteCustomerMain((bsCustomerMain.Current as CustomerMain));
                if (i > 0)
                {
                    MessageBox.Show("删除成功");
                    bsCustomerMain.RemoveCurrent();
                    bsCustomerFinance.DataSource = null;
                    bsCustomerDeliver.DataSource = null;
                    bsCustomerContract.DataSource = null;
                }
                else
                {
                    MessageBox.Show("删除失败，请联系开发者");
                }
            }
            else
            {
                MessageBox.Show("请选择需要删除的客户");
            }
            
        }

        /// <summary>
        /// 根据客户编号和客户名称检查是否已经存在客户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCheckAlreadyExists_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxCustomerCode.Text.Trim()))
            {
                MessageBox.Show("请输入要查询的客户编号");
            }
            else
            {
                clearDataGridView();
                CustomerMain customerMain = CustomerMainService.CheckCustomerMainAlreadyExists(textBoxCustomerCode.Text.Trim(), textBoxCustomerName.Text.Trim());
                if (customerMain != null)
                {
                    showCustomerMainDetail(customerMain);
                }
                else
                {
                    MessageBox.Show("未查询到该客户编号相关信息");
                }
            }
            
        }
        /// <summary>
        /// 根据客户编号和客户名称查询到的客户信息显示到界面
        /// </summary>
        /// <param name="customerMain"></param>
        private void showCustomerMainDetail(CustomerMain customerMain)
        {
            bsCustomerContract.DataSource = customerMain.customerContractList;
            dataGridViewContract.DataSource = bsCustomerContract;

            bsCustomerFinance.DataSource = customerMain.customerFinanceList;
            dataGridViewFinance.DataSource = bsCustomerFinance;

            bsCustomerDeliver.DataSource = customerMain.customerDeliverList;
            dataGridViewDeliver.DataSource = bsCustomerDeliver;
        }

        private void clearDataGridView()
        {
            bsCustomerContract.Clear();
            bsCustomerFinance.Clear();
            bsCustomerDeliver.Clear();
        }
        /// <summary>
        /// 添加联系人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddContract_Click(object sender, EventArgs e)
        {
            //封装公共池客户联系人对象
            CustomerContract customerContract = new CustomerContract();
            customerContract.ContactName = textBoxContactName.Text.Trim();
            customerContract.ContractSex = this.comboBoxContractSex.SelectedItem.ToString();
            customerContract.ContactTelephone = this.textBoxContactTelephone.Text.Trim();
            customerContract.ContractPostion = textBoxContractPostion.Text.Trim();
            customerContract.ContractWeChat = textBoxContractWeChat.Text.Trim();
            customerContract.ContractQq = textBoxContractQq.Text.Trim();
            customerContract.ContractBirthday = dateTimePickerCustomerBirthday.Value;
            customerContracts.Add(customerContract);
            bsCustomerContract.DataSource = customerContracts;
            dataGridViewContract.DataSource = bsCustomerContract;
            bsCustomerContract.ResetBindings(true);
        }

        /// <summary>
        /// 输入完成客户编号后，检查是否已经有了
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxCustomerCode_Validated(object sender, EventArgs e)
        {
            CustomerMain customerMain = CustomerMainService.CheckCustomerMainAlreadyExists(textBoxCustomerCode.Text.Trim(), textBoxCustomerName.Text.Trim());
            if (customerMain != null)
            {
                showCustomerMainDetail(customerMain);
                //如果已经有了这个客户编号的数据，则将对应的行数据选中
                foreach (CustomerMain item in bsCustomerMain)
                {
                    if (customerMain.Id == item.Id)
                    {
                        dataGridViewCustomerMain.Rows[bsCustomerMain.IndexOf(item)].Selected = true;
                    }
                }
            }
            else
            {
                clearCustomerMainDetail();
            }
            if (string.IsNullOrEmpty(textBoxCustomerCode.Text.Trim()))
            {
                buttonSave.Enabled = false;
            }
            else
            {
                buttonSave.Enabled = true;
            }
        }

        private void clearCustomerMainDetail()
        {
            bsCustomerContract.DataSource = null;
            bsCustomerDeliver.DataSource = null;
            bsCustomerFinance.DataSource = null;
        }

        private void dataGridViewContract_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                //从datagridview删除
                if (dataGridViewContract.Columns[e.ColumnIndex].Name == "C删除")
                {
                    bsCustomerContract.RemoveCurrent();
                }
            }
        }

        private void dataGridViewContract_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                //显示点击的行信息
                if (dataGridViewContract.Columns[e.ColumnIndex].Name != "C删除")
                {
                    customerContract = bsCustomerContract.Current as CustomerContract;
                    textBoxContactName.Text = customerContract.ContactName;
                }
            }
        }
        /// <summary>
        /// 添加联系人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddDeliver_Click(object sender, EventArgs e)
        {
            //封装公共池客户收货信息对象
            CustomerDeliver customerDeliver = new CustomerDeliver();
            customerDeliver.DeliverName = textBoxDeliverName.Text.Trim();
            customerDeliver.DeliverTelephone = textBoxContactTelephone.Text.Trim();
            customerDeliver.DeliverAddress = textBoxDeliverAddress.Text.Trim();
            customerDelivers.Add(customerDeliver);
            bsCustomerDeliver.DataSource = customerDelivers;
            dataGridViewDeliver.DataSource = bsCustomerDeliver;
            bsCustomerDeliver.ResetBindings(true);
        }
        /// <summary>
        /// 添加账户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddFinance_Click(object sender, EventArgs e)
        {
            //封装公共池客户账户信息对象
            CustomerFinance customerFinance = new CustomerFinance();
            customerFinance.FinanceBank = textBoxFinanceBank.Text.Trim();
            customerFinance.FinanceCode = textBoxFinanceCode.Text.Trim();
            customerFinance.FinanceSwift = textBoxFinanceSwift.Text.Trim();
            customerFinance.FinanceCurrency = textBoxFinanceCurrency.Text.Trim();
            customerFinance.FinanceBigBank = textBoxFinanceBigBank.Text.Trim();
            customerFinances.Add(customerFinance);
            bsCustomerFinance.DataSource = customerFinances;
            dataGridViewFinance.DataSource = customerFinances;
            bsCustomerFinance.ResetBindings(true);
        }

        private void dataGridViewDeliver_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //从datagridview删除
            if (dataGridViewDeliver.Columns[e.ColumnIndex].Name == "D删除")
            {
                bsCustomerDeliver.RemoveCurrent();
            }
        }

        private void dataGridViewFinance_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //从datagridview删除
            if (dataGridViewFinance.Columns[e.ColumnIndex].Name == "E删除")
            {
                bsCustomerFinance.RemoveCurrent();
            }
        }

        public void ClearCntrValue(Control parContainer)
        {
            for (int index = 0; index < parContainer.Controls.Count; index++)
            {
                // 如果是容器类控件，递归调用自己
                if (parContainer.Controls[index].HasChildren)
                {
                    ClearCntrValue(parContainer.Controls[index]);
                }
                else
                {
                    switch (parContainer.Controls[index].GetType().Name)
                    {
                        case "TextBox":
                            parContainer.Controls[index].Text = "";
                            break;
                        case "RadioButton":
                            ((RadioButton)(parContainer.Controls[index])).Checked = false;
                            break;
                        case "CheckBox":
                            ((CheckBox)(parContainer.Controls[index])).Checked = false;
                            break;
                        case "ComboBox":
                            ((ComboBox)(parContainer.Controls[index])).Text = "";
                            break;
                    }
                }
            }
        }
    }
}
